<template>
  <Drawer
    width="46rem"
    title="评论详情"
    :visible="visible"
    @close="onCancel"
    :destroy-on-close="true"
  >
    <Spin :spinning="loading">
      <Form
        ref="formRef"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
        :scroll-to-first-error="true"
        :colon="true"
        :model="form"
      >
        <FormItem label="ID">
          <TypographyText copyable>{{ comment?.id }}</TypographyText>
          <Divider type="vertical" />
          <TypographyText copyable>{{ comment?._id }}</TypographyText>
        </FormItem>
        <FormItem label="发布于">
          {{ stringToYMD(comment?.create_at!) }}
        </FormItem>
        <FormItem label="最后修改于">
          {{ stringToYMD(comment?.update_at!) }}
        </FormItem>
        <FormItem label="用户头像">
          <CommentAvatar size="large" :comment="comment!" />
        </FormItem>
        <FormItem :name="['author', 'name']" label="用户昵称">
          <Input v-model:value="form.author.name">
            <template #prefix>
              <UserOutlined />
            </template>
          </Input>
        </FormItem>
        <FormItem :name="['author', 'email']" label="用户邮箱">
          <Input type="email" v-model:value="form.author.email">
            <template #prefix>
              <MailOutlined />
            </template>
          </Input>
        </FormItem>
        <FormItem :name="['author', 'site']" label="用户网址">
          <Input type="url" v-model:value="form.author.site">
            <template #suffix>
              <SendOutlined @click="handleOpen(form.author.site!)" />
            </template>
          </Input>
        </FormItem>
        <FormItem label="IP 地址">
          <UniversalText :text="comment?.ip!" copyable />
        </FormItem>
        <FormItem label="IP 地理位置">
          <IPLocation :data="comment?.ip_location" fullname />
        </FormItem>
        <FormItem label="终端">
          <UniversalText :text="parseBrowser(comment?.agent!)" placeholder="未知浏览器" />
          <Divider type="vertical" />
          <UniversalText :text="parseOS(comment?.agent!)" placeholder="未知系统" />
          <Divider type="vertical" />
          <UniversalText :text="parseDevice(comment?.agent!)" placeholder="未知设备" />
        </FormItem>
        <FormItem name="likes" label="被赞">
          <InputNumber v-model:value="form.likes" placeholder="多少">
            <template #addonBefore>
              <LikeOutlined />
            </template>
          </InputNumber>
        </FormItem>
        <FormItem name="dislikes" label="被踩">
          <InputNumber v-model:value="form.dislikes" placeholder="多少">
            <template #addonBefore>
              <DislikeOutlined />
            </template>
          </InputNumber>
        </FormItem>
        <FormItem label="宿主页面">
          <Button type="link" target="_blank" :href="getBlogURLByPostID(comment?.post_id!)">
            <template #icon>
              <LinkOutlined />
            </template>
            <template v-if="comment?.post_id === COMMENT_GUESTBOOK_POST_ID">留言板</template>
            <template v-else>{{ commentArticle?.title }}</template>
            <Divider type="vertical" />
            <span>#{{ comment?.id }}</span>
          </Button>
        </FormItem>
        <FormItem v-if="comment?.pid" label="父级评论">
          <TypographyText strong>#{{ comment?.pid }}</TypographyText>
        </FormItem>
        <FormItem name="state" label="状态">
          <Select v-model:value="form.state">
            <SelectOption v-for="(state, j) in commentStates" :key="j" :value="state.id">
              <Space>
                <component :is="state.icon"></component>
                {{ state.name }}
              </Space>
            </SelectOption>
          </Select>
        </FormItem>
        <FormItem name="content" label="评论内容">
          <UniversalEditor
            :value="form.content"
            :min-rows="14"
            :max-rows="18"
            :disabled-minimap="true"
            :disabled-cache-draft="true"
          />
        </FormItem>
        <FormItem label="自定义扩展" extra="可以为当前评论增加自定义扩展属性">
          <FormDataKeyValue v-model:value="form.extends" />
        </FormItem>
        <FormItem label="">
          <Button :loading="loading" type="primary" @click="handleSubmit">
            <template #icon>
              <CheckOutlined />
            </template>
            提交更新
          </Button>
        </FormItem>
      </Form>
    </Spin>
  </Drawer>
</template>

<script setup lang="ts">
import {
  Drawer,
  Spin,
  Form,
  FormItem,
  TypographyText,
  Divider,
  Input,
  InputNumber,
  Button,
  Select,
  SelectOption,
  Space,
  FormInstance,
} from 'ant-design-vue'
import {
  UserOutlined,
  MailOutlined,
  SendOutlined,
  LikeOutlined,
  DislikeOutlined,
  LinkOutlined,
  CheckOutlined,
} from '@ant-design/icons-vue'
import { PropType, reactive, ref, watch } from 'vue'
import {
  COMMENT_GUESTBOOK_POST_ID,
  Comment,
  CommentState,
  commentStates,
} from '@/constants/comment'

import UniversalText from '@/components/UniversalText/index.vue'
import UniversalEditor from '@/components/UniversalEditor/index.vue'
import IPLocation from '@/components/IPLocation/index.vue'
import FormDataKeyValue from '@/components/FormDataKeyValue/index.vue'
import CommentAvatar from '@/pages/comment/Avatar.vue'
import { parseBrowser, parseDevice, parseOS } from '@/transformers/ua'
import { stringToYMD } from '@/transformers/date'
import { getBlogURLByPostID } from '@/transformers/url'
import { Article } from '@/constants/article'
import { useLoading } from '@/handcer'
import { getArticle } from '@/store/article'

const props = defineProps({
  loading: {
    type: Boolean,
    required: true,
  },
  visible: {
    type: Boolean,
    required: true,
  },
  comment: {
    type: Object as PropType<Comment | null>,
  },
  onSubmit: {
    type: Function as PropType<(comment: Comment) => void>,
    required: true,
  },
  onCancel: {
    type: Function as PropType<(e: MouseEvent) => void>,
    required: true,
  },
})

const DEFAULT_COMMENT = (): Comment => ({
  id: 0,
  _id: '',
  pid: 0,
  post_id: 0,
  content: '',
  agent: '',
  state: CommentState.Published,
  likes: 0,
  dislikes: 0,
  author: {
    name: '',
    site: '',
    email: '',
    email_hash: null,
  },
  ip: null,
  ip_location: null,
  update_at: '',
  create_at: '',
  extends: [],
})

const formRef = ref<FormInstance>()
const form = reactive<Comment>(DEFAULT_COMMENT())

const rules = reactive({
  author: {
    name: [{ required: true, message: '请输入评论人名称' }],
    email: [{ type: 'email', message: '请输入正确的邮箱' }],
    site: [{ type: 'url', message: '请输入正确的 URL' }],
  },
  likes: [{ required: true, message: '必填' }],
  dislikes: [{ required: true, message: '必填' }],
  state: [{ required: true, message: '请选择状态' }],
  content: [{ required: true, message: '请输入内容' }],
})

const loadingComment = useLoading()
const commentArticle = ref<Article | null>(null)
const handleSubmit = () => {
  formRef.value
    ?.validate()
    .then(() => {
      props.onSubmit(form)
    })
    .finally(() => {
      formRef.value?.resetFields()
    })
}

// 打开站点
const handleOpen = (url: string | null): void => {
  url && window.open(url)
}

// 获取文章详情
const fetchArticle = (articleId: number) => {
  loadingComment.promise(getArticle(articleId)).then((result) => {
    commentArticle.value = result
  })
}

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      const targetComment = props.comment
      if (targetComment) {
        Object.assign(form, targetComment)
        if (targetComment.post_id !== COMMENT_GUESTBOOK_POST_ID) {
          fetchArticle(targetComment.post_id)
        }
      }
    }
  }
)
</script>

<style lang="less" scoped>
.postIdInput {
  padding: 10px;
  input[type='number'] {
    -moz-appearance: textfield;
    &::-webkit-outer-spin-button,
    &::-webkit-inner-spin-button {
      -webkit-appearance: none !important;
      margin: 0;
    }
  }
}

.comment {
  .toolbar {
    display: flex;
    justify-content: space-between;

    .select {
      width: 120px;

      &.type {
        width: 150px;
      }
    }
    .search {
      width: 260px;
    }
  }
}

.content {
  overflow-wrap: anywhere;
  margin-bottom: 0 !important;
}
</style>
